package org.liufeng.course.service;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;

import org.json.JSONObject;
import org.liufeng.course.util.StrTools;

/**
 * 
 * @author liufeng
 * @date 2013-10-21
 */
public class RequestService {
	/**
	 * 发起http请求获取返回结果
	 * 
	 * @param requestUrl 请求地址
	 * @return
	 */
	public static String httpRequest(String requestUrl,String type) {
		StringBuffer buffer = new StringBuffer();
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();

			httpUrlConn.setDoOutput(false);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			httpUrlConn.setRequestMethod("GET");
			httpUrlConn.setConnectTimeout(2000);
			httpUrlConn.setReadTimeout(2000);
			httpUrlConn.connect();

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, type);
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();

		} catch (Exception e) {
		}
		return buffer.toString();
	}

	/**
	 * utf编码
	 * 
	 * @param source
	 * @return
	 */
	public static String urlEncodeUTF8(String source) {
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获得天气
	 * 
	 * @param source
	 * @return
	 */
	public static String getWeather(String type) {
		String dst = null;

		// 组装查询地址
		//String requestUrl = "http://m.weather.com.cn/data/101210405.html";
		/*String requestUrl = "http://api2.sinaapp.com/search/weather/?appkey=0020130430&appsecert=fa6095e113cd28fd&reqtype=text&keyword=%E5%A5%89%E5%8C%96";
		*/
		String requestUrlsk = "http://www.weather.com.cn/data/sk/101210405.html";
		// 查询并解析结果
		try {
			if(type.equals("B1")){//天气预报
			// 查询并获取返回结果中国天气网
			/*String json = httpRequest(requestUrl,"utf-8");
			System.out.println(urlEncodeUTF8(json));
            JSONObject jsonObject = new JSONObject(json);
            JSONObject value = new JSONObject(jsonObject.getString("weatherinfo").toString());
            dst = "[中国气象信息网提供"+"\n"+value.get("date_y")+"，"+value.getString("week")+"]\n"+
                  "今日天气："+"\n"+value.get("img_title1")+","+value.get("temp1")+","+value.get("wind1")+"\n"+
                  "穿衣指数："+"\n"+value.get("index_d")+"\n"+
                  "明日天气："+"\n"+value.get("img_title2")+","+value.get("temp2")+","+value.get("wind2")+"\n"+
                  "后日天气："+"\n"+value.get("img_title3")+","+value.get("temp3")+","+value.get("wind3")+"\n\n";
							
				
				//方倍工作室
				String json = httpRequest(requestUrl,"utf-8");
				JSONObject jsonObject = new JSONObject(json);
	            JSONObject value = new JSONObject(jsonObject.getString("text").toString());
	            dst = "[中国气象信息网提供]"+"\n"+value.getString("content")+"\n\n";
	            */
								
				String html = httpRequest("http://www.fhqx.net/dqtq.aspx","gb2312");
				Pattern p = Pattern.compile("(\\[.*\\].*\\s+)(?=\\[)");
				Matcher m = p.matcher(html);
				String baccont = "暂无天气信息";
					if (m.find()) {
						String cont = m.group(0);
						baccont=cont.replaceAll("<(?!\\?)[^>]+>" ,"").replace("\">", "\n");
					}
				dst= baccont.trim();
				
			}else if(type.equals("B2")){//天气实况
				
				String jsonsk = httpRequest(requestUrlsk,"utf-8");
				System.out.println(urlEncodeUTF8(jsonsk));
	            JSONObject jsonObject = new JSONObject(jsonsk);
	            JSONObject value = new JSONObject(jsonObject.getString("weatherinfo").toString());

	            dst = "= 奉化天气实况  ="+"\n"+
	            	  "获取时间： "+ value.get("time")+"\n"+
	                  "实时气温："+value.get("temp")+"摄氏度"+"\n"+
	                  "实时风况："+value.get("WD")+","+value.get("WS")+"\n"+
	                  "实时湿度："+value.get("SD")+"";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dst;
	}
	
	
	
	public static String getTF() {
		String html = httpRequest("http://typhoon.weather.com.cn/index.shtml","utf-8");
		Pattern p = Pattern.compile("<div class=\"borBox blockLC\">.*</a></p>");
		Matcher m = p.matcher(html);

		
		String baccont = "暂无台风信息";
		String aa = "";
		if (m.find()) {
			String[] cont = m.group().split("<p>");
			Pattern pp = Pattern.compile("</span><b>.*</b></h2>");
			Matcher mm = pp.matcher(m.group());
			
			if(mm.find()){
				String[] conta = mm.group().split("<b>");
				aa = conta[1].replace("</b></h2>", "");
			}
			baccont = aa+"\n"+cont[1].replace("</a></p>", "");
			baccont = baccont.replace("<P>", "").trim();
			baccont = baccont.replace("</P>", "").trim();
			baccont = baccont.replace("<BR>", "").trim();
		}
		return baccont;
	}
	
	public static Map<String, String> getYJ() throws UnsupportedEncodingException {
		String html = httpRequest("http://nb.zj.weather.com.cn/web/tqjb.asp","gb2312");
		Pattern p = Pattern.compile("<font style=\"font-size:20px\" color=\"black\">.*<iframe");
		//String html = httpRequest("http://www.fhqx.net/","gb2312");
		//Pattern p = Pattern.compile("<span id="lb_yjxhfb">.*</span>");
		
		Pattern q = Pattern.compile("<font style=\"font-size:24px\">.*</b></font>");
		Matcher m = p.matcher(html);
		Matcher n = q.matcher(html);
		String baccont = "暂无预警信息";
		String aa = "";
		if (n.find()){
			String[] cont = n.group().split("<b>");
			aa = cont[1].replace("</b></font>", "");
		}
		if (m.find()) {
			String[] cont = m.group().split("&nbsp;&nbsp;");
			baccont = cont[1].replace("<iframe", "");
		}
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("title", aa);
		map.put("cont", baccont.trim());
		return map;
	}
	
	
/*	public static Map<String, String> getYJzj() throws UnsupportedEncodingException {
		String html = httpRequest("www.zjmb.gov.cn/weather/wapdb/wapstyjxxdetail.jsp?yj_art_id=0","utf-8");
		
		Pattern p = Pattern.compile("<ul class=\"yjxxlist\">.*</DIV>");
		//String html = httpRequest("http://www.fhqx.net/","gb2312");
		//Pattern p = Pattern.compile("<span id="lb_yjxhfb">.*</span>");
		
		Pattern q = Pattern.compile("<li>.*</li");
		Matcher n = p.matcher(html);
		Matcher m = q.matcher(html);
		String baccont = "暂无预警信息";
		String aa = "";
		if (n.find()){
			String[] cont = n.group().split("<li>");
			aa = cont[1].replace("</li>", "");
		}
		if (m.find()) {
			String[] cont = m.group().split("&nbsp;&nbsp;");
			baccont = cont[1].replace("", "");
		}
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("title", aa);
		map.put("cont", baccont.trim());
		return map;
	}*/
	public static Map getYJ2() throws UnsupportedEncodingException {
		String html = httpRequest("http://www.fhqx.net/","gb2312");
		Pattern p = Pattern.compile("<span id=\"lb_yjxhfb\">.*</span></div></td>");
		Matcher m = p.matcher(html);
		String baccont = "暂无预警信息...";
		if (m.find()){
			String cont = m.group().replace("<span id=\"lb_yjxhfb\">", "");
			baccont = cont.replace("</span></div></td>","");
		}
		Map map = new HashMap();
		map.put("title", "奉化市气象台");
		map.put("cont", baccont.trim());
	return map;
	}

	public static String getYQ() {
		String html = httpRequest("http://www3.nbswz.com.cn/swznew/other/Rain.aspx","gb2312");
		Pattern p = Pattern.compile("<a class=\"TROWNAME\" href=\"#\">奉化市</a>.*<a class=\"TROWNAME\" href=\"#\">象山县</a>");
		Matcher m = p.matcher(html);
		String baccont = "";
		if (m.find()) {
			String[] count = m.group().replaceAll("<td >", "").split("</td>");
			String[] count4 = count[4].replaceAll("&nbsp;", "").split(">");
				baccont+="今日雨量:"+count[1]+"mm\n"+
				"昨日雨量:"+count[2]+"mm\n"+
				"前日雨量:"+count[3]+"mm\n"+
				"三日累计雨量:"+count[4]+"mm";
				//"最大雨量点(今日):"+count5[2].replace("</span", "")+"mm;"+count5[5].replace("</span", "")+"mm;";
		}
		return baccont;
		
	}
	public static String getYTtime() {
		String html = httpRequest("http://agora.ex.nii.ac.jp/digital-typhoon/","utf-8");
		Pattern p = Pattern.compile("<div class=\"TROPIC\"><table class=\"TROPIC\" cellspacing=\"1\">.*<tr><td colspan=\"2\">");
		Matcher m = p.matcher(html);
		String baccont = "暂无云图更新时间";

		if (m.find()) {
			String[] cont = m.group().split("<th colspan=\"2\">");
			baccont = cont[1].replace("(JST)</th></tr><tr><td colspan=\"2\">", "").trim(); 
			
			
		}
		return baccont.trim();
	}
/*	
	public static String getWeibo() {
		String html = httpRequest("http://t.qq.com/fhsljchslz","utf-8");
		Pattern p = Pattern.compile("<div class=\"msgCnt\">.*</div>");
		Matcher m = p.matcher(html);
		String baccont = "暂无动态";

		if (m.find()) {
			String[] cont = m.group().split("<div class=\"msgCnt\">");
			baccont = cont[1].replace("", "").trim();
			
			
		}
		return baccont.trim();
	}*/
	//短时预报
	public static String getDSYB() {
		String html = httpRequest("http://zj.weather.com.cn/qxsj/dsyb/index.shtml","utf-8");
		Pattern p = Pattern.compile("<!--短时预报内容start-->.*<!--短时预报内容end-->");
		Matcher m = p.matcher(html);
		String baccont = "暂无短时预报，请稍后再试";

		if (m.find()) {
			String[] cont = m.group().split("<dl id=\"mainContent\"><p>");
			baccont = cont[1].replace("</p></dl></div>", "").trim();
			baccont = baccont.replace("<!--短时预报内容end-->", "").trim();
			baccont = baccont.replace("<P>", "").trim();
			baccont = baccont.replace("</P>", "").trim();
			baccont = baccont.replace("<BR>", "").trim();
			
			
		}
		return baccont.trim();
	}
	
	///t=5 最近24小时 t=6 最近48小时  降水
	public static String getJS(Integer ids) {
		String html = httpRequest("http://www.fhqx.net/zhgc/index.aspx?t="+ids,"gb2312");
		Pattern p = Pattern.compile("<td align=\"center\" >.*</td>");
		Matcher m = p.matcher(html);
		Pattern p2 = Pattern.compile("<span[^>]*>(.*?)<\\s*/\\s*span>");
		Matcher m2 = p2.matcher(html);
		String baccont =  "";
		if (m2.find()) {
			baccont = m2.group().replaceAll("<span[^>]*>", "").replaceAll("<\\s*/\\s*span>", "").replaceAll("&nbsp;", "")+"\n";
		}
		if (m.find()) {
			String[] tss = m.group().replaceAll("<tr>", "").split("</tr>");
			for(int i=1;i<tss.length;i++){
				String[] tssy = tss[i].replaceAll("<td[^>]*>", "").split("</td>");
				baccont+=tssy[1].trim()+":"+tssy[2].trim()+"mm\n";
			}
		}

		return baccont.trim();
	}
	
	
	public static String getJS2() {
		String html = httpRequest("http://www.fhqx.net/zhgc/index.aspx?t=6","gb2312");
		Pattern p = Pattern.compile("<span[^>]*>(.*?)<\\s*/\\s*span>");
		Matcher m = p.matcher(html);
		String baccont =  "1";
		if (m.find()) {
			baccont = m.group().replaceAll("<span[^>]*>", "").replaceAll("<\\s*/\\s*span>", "").replaceAll("&nbsp;", "");
		}
		return baccont.trim();
	}
	
	//三防信息封装
	public static Map getSFXX(String stcd,String flag) {
		Map map = new HashMap();
		try{
			String url = "http://fhs.fxpt.org:8090/HyDroDataService/service/queryZZSpace.action?stcd="+stcd;
			if(flag!=null&&!flag.equals("")&&flag.equals("reser")){
				url = "http://fhs.fxpt.org:8090/HyDroDataService/service/queryRRSpace.action?stcd="+stcd;
			}
			System.out.print("**********"+url);
			String json = RequestService.httpRequest(url,"utf-8");
			net.sf.json.JSONObject ob=net.sf.json.JSONObject.fromObject(json);
			String totalCount = ob.getString("totalCount");
			if(totalCount.equals("0")){
				map.put("flag", "F");//实时水位
			}else{
			JSONArray array=ob.getJSONArray("result");
			net.sf.json.JSONObject obnew=array.getJSONObject(0);
			map.put("sssw", StrTools.isStrNull(obnew.get("Z"))+"m");//实时水位
			map.put("sskr", StrTools.isStrNull(obnew.get("CP"))+"万m³");
			map.put("jjsw", StrTools.isStrNull(obnew.get("WRZ"))+"m");//警戒水位
			map.put("xsbl", StrTools.isStrNull(obnew.get("MOD")));  
			map.put("isWarn", StrTools.isStrNull(obnew.get("isWarn")).equals("1")?"是":"否");
			map.put("sTime", StrTools.isStrNull(obnew.get("TM")));
			map.put("adcdName", StrTools.isStrNull(obnew.get("adcdName"))); 
			map.put("stlc", StrTools.isStrNull(obnew.get("STLC")));//站点位置
			map.put("wxsw", StrTools.isStrNull(obnew.get("DPZ")));//危险水位
			map.put("rvnm", StrTools.isStrNull(obnew.get("RVNM")));//所在流域/水系
			map.put("stnm", StrTools.isStrNull(obnew.get("STNM")));//站名
			map.put("cityName", StrTools.isStrNull(obnew.get("CityName")));//站名
			map.put("flag", "T");//实时水位
			}
		}catch(Exception e){
			map.put("flag", "F");
		}
		return map;
	}
	
//获取空气质量指数	
	public static String getPm25() {
		String html = httpRequest("http://www.cnpm25.cn/City/ningbo.html","utf-8");
		//Pattern p = Pattern.compile("<!-- ----- flash start ----------->(.*?)<!------- flash end ----------->");
		Pattern p = Pattern.compile("var jin_value(.*) var tishi");
		Matcher m = p.matcher(html);
		String baccont =  "1";
		String baccont1 = "0";
		if (m.find()) {
			baccont = m.group();
			System.out.println(baccont);
			Pattern pattern = Pattern.compile("jin_value = \"d*[0-9]*");
			Matcher matcher = pattern.matcher(baccont.toString());
			while(matcher.find()){
				String str = matcher.group();
				String value = str.substring(str.indexOf("\"")+1,str.length());
				baccont1=baccont1+value+";";
			}
		}
		return baccont1.trim();
	}
	/**
	 * 获得天气
	 * 
	 * @param source
	 * @return
	 */
	public static String getWeather1() {
		String dst = null;
		String requestUrlsk = "http://www.weather.com.cn/data/sk/101210405.html";
		// 查询并解析结果
		try {
				String html = httpRequest("http://www.fhqx.net/dqtq.aspx","gb2312");
				Pattern p = Pattern.compile("(\\[.*\\].*\\s+)(?=\\[)");
				Matcher m = p.matcher(html);
				String baccont = "暂无天气信息";
				if (m.find()) {
					String cont = m.group(0);
					baccont=cont.replaceAll("<(?!\\?)[^>]+>" ,"").replace("\">", "\n");
				}
				dst= baccont.trim();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dst;
	}
	
	
	public static void main(String[] ar) throws Exception {
/*		System.out.println(getYTtime());
		System.out.println(getWeibo());
		Map map=	getYJzj();
		System.out.println(map.get("title"));
		System.out.println(map.get("cont"));*/

		//System.out.println(getWeather1());
		//System.out.println(getYQ());
		//System.out.println(getDSYB());
		//System.out.println(getTF());
		System.out.println(getWeather("B1"));
		//System.out.println(getJS(6));
//		Map map = getSFXX("20","reser");
//		StringBuffer cont = new StringBuffer();
//		
//		cont.append("湖头渡G潮位站数据:");
//		cont.append("实时潮位：").append(map.get("sssw")).append("\n");
//		cont.append("警戒潮位：").append(map.get("jjsw")).append("\n");
//		cont.append("是否超出警戒潮位：").append(map.get("isWarn"));
//		cont.append("更新时间：").append(map.get("sTime")).append("\n").append(map.get("flag"));
//		System.out.print(cont.toString());
		
	}
	

}
